﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleAppDemo {
    public class ManualResetEventManage {
        private ManualResetEvent manualEvent;
        public ManualResetEventManage(ManualResetEvent manualEvent)
        {
            this.manualEvent = manualEvent;
        }
        public void ThreadProc()
        {
            Console.WriteLine(Thread.CurrentThread.Name + "starts and calls manualEvent.WaitOne()");
            manualEvent.WaitOne();
            Console.WriteLine(Thread.CurrentThread.Name + "ends.");
        }
    }

    public class MREDemo {
        private ManualResetEvent _mre;
        public MREDemo()
        {
            this._mre = new ManualResetEvent(true);
        }
        public void CreateThreads()
        {
            Thread t1 = new Thread(new ThreadStart(Run));
            t1.Start();

            Thread t2 = new Thread(new ThreadStart(Run));
            t2.Start();
        }
        public void Set()
        {
            _mre.Set();
        }
        public void Reset()
        {
            _mre.Reset();
        }
        public void Run()
        {
            string strThreadID = string.Empty;
            try
            {
                while (true)
                {
                    this._mre.WaitOne();
                    strThreadID = Thread.CurrentThread.ManagedThreadId.ToString();
                    Console.WriteLine("Thread(" + strThreadID + ") is running...");
                    Thread.Sleep(5000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("线程(" + strThreadID + ")发生异常！错误描述：" + ex.Message.ToString());
            }
        }
    }
}
